<template>
    <div class="exam-container">
        <div class="filter-section">
            <div style="display: flex">
                <div style="width: 90px">
                    课程分类:
                </div>
                <el-radio-group v-model="radio">
                    <el-radio>全部</el-radio>
                    <el-radio
                            v-for="item in courseOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                    >
                        <span>{{ item.name }} </span>
                    </el-radio>
                </el-radio-group>
            </div>
            <!--  表格-->
            <div>
                <el-table :data="tableData" :row-style="{ height: '77px' }"
                          style="width: 100%;height: 50vh;font-size: 15px;" border>
                    <!-- 各列定义 -->
                    <el-table-column prop="name" label="资料名称" width="auto" align="center"/>
                    <el-table-column prop="courseName" label="课程名称" width="auto" align="center"/>
                    <el-table-column prop="flow" label="是否查看" align="center" width="100">
                                    <template #default="scope">
                                        <el-tag type="warning" v-if="scope.row.flow === 0 || scope.row.flow === null">未查看</el-tag>
                                        <el-tag type="success" v-else-if="scope.row.flow === 1">已查看</el-tag>
                                    </template>
                                </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="auto" align="center"/>
                    <el-table-column label="操作" fixed="right" width="100" align="center">
                        <template v-slot="scope">
                            <el-button icon="View" size="small" type="success" @click="openFile(scope.row)">查看
                            </el-button>
                            <el-button icon="Download" size="small" type="warning" @click="download(scope.row.url)">
                                下载
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页组件 -->
            <div style="justify-content: center;">
                <el-pagination
                        :current-page="currentPage"
                        :page-size="pageSize"
                        :page-sizes="[10, 20, 30, 50]"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        :background="true"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </div>

    <el-dialog title="文件预览" v-model="openItemFileDialog" :style="dialogStyle" top="5vh" class="custom-preview-dialog"
               @close="closeFile">
        <div class="preview-container" v-if="openItemFileDialog">
            <!-- PDF 预览 -->
            <vue-office-pdf v-if="fileExt === 'docx' || fileExt === 'doc'" :src="pdfSrc" style="height: 70vh" />

            <iframe v-if="fileExt !== 'docx' && fileExt !== 'doc'" :src="pdfSrc" frameborder="0"
                    style="background-color: #fff;width: 100%; height: 70vh"></iframe>
        </div>
    </el-dialog>
</template>
<script>
    import {serverIp} from "~/utils/config.js"
    import request from "~/utils/request.js";
    import VueOfficePdf from '@vue-office/pdf'

    export default {
        components: {
            VueOfficePdf
        },
        data() {
            return {
                windowWidth: window.innerWidth,
                openItemFileDialog: false,
                dialogVisible: false,
                serverIp: serverIp, //附件上传路径
                pdfSrc: "",
                fileExt: '',       // 文件扩展名
                form: {},
                radio: '', // 课程分类
                courseOptions: [],
                // 资源数据
                tableData: [],
                search: '',
                currentPage: 1,
                pageSize: 10,
                total: 0,
                rules: [],
                userId:this.$store.state.user.id, // 用户id
            }
        },
        computed: {
            dialogStyle() {
                return this.windowWidth <= 768 ? { width: '90%' } : { width: '50%' };
            },
        },
        mounted() {
            window.addEventListener('resize', this.handleResize);
        },
        beforeUnmount() {
            window.removeEventListener('resize', this.handleResize);
        },
        activated() {
            this.load()
            this.getCourseOptions()
        },
        watch: {
            radio() {
                this.load();
            },
        },
        methods: {
            handleResize() {
                this.windowWidth = window.innerWidth;
            },
            load() {
                request.get("/teach-plan/stuFindResourcePage", {
                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        name: this.search,
                        typeId: this.radio,
                        userId: this.userId,
                    }
                }).then(res => {
                        this.tableData = res.data.records;
                        this.total = res.data.total;
                    })
            },
            getCourseOptions() {
                request.get("/course-type/all").then(res => {
                    this.courseOptions = res.data
                })
            },
            download(url) {
                const fileName = `${encodeURIComponent(url.split('/').pop())}`
                window.open(serverIp + "/api/files/download/" + fileName)
            },
            handleCurrentChange(item) {
                // 改变当前页码触发
                this.currentPage = item
                this.load()
            },
            handleSizeChange(item) {   // 改变当前每页的个数触发
                this.pageSize = item
                this.load()
            },
            async openFile(scope) {
                const fileUrl = scope.url;
                this.openItemFileDialog = true
                const fullUrl = serverIp + fileUrl
                this.fileExt = fileUrl.split('.').pop().toLowerCase()
                console.log(this.fileExt)
                try {
                    if (this.fileExt !== "docx" && this.fileExt !== "doc") {
                        this.pdfSrc = fullUrl
                    } else {
                        const previewUrl = `/api/files/preview/${encodeURIComponent(fileUrl.split('/').pop())}`
                        const response = await fetch(previewUrl)
                        const blob = await response.blob()
                        this.pdfSrc = URL.createObjectURL(blob)
                    }
                } catch (error) {
                    this.$message.error('文档预览失败: ' + error.message)
                }
                if(scope.flow === 0 || scope.flow === null){
                    request.get("/teach-plan-sign/stuUpdateTeachPlanSignFlow",{
                        params:{
                            stuId:this.$store.state.user.id, // 用户id
                            teachPlanId:scope.id, // 资源id
                        }
                    }).then(res => {
                        this.load()
                    })
                }

            },
            closeFile() {
                this.openItemFileDialog = false
                // 释放URL对象
                if (this.pdfSrc && this.pdfSrc.startsWith('blob:')) {
                    URL.revokeObjectURL(this.pdfSrc);
                }
                this.pdfSrc = "";

                // 销毁iframe的资源
                const iframes = document.querySelectorAll('iframe');
                iframes.forEach(iframe => {
                    iframe.src = 'about:blank';
                });
            },
        }
    }
</script>
<style scoped>
    .exam-container {
        padding: 10px;
        display: flex;
        flex-direction: column;
    }

    .filter-section {
        background: #fff;
        padding: 10px;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .filter-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .filter-group span {
        font-size: 16px;
        color: #333;
    }

    /* 修改分页布局 */
    .el-pagination {
        display: flex;
        justify-content: center;
        margin-top: 10px !important;
    }

    @media (max-width: 768px) {
        /* 分页样式 */
        .el-pagination {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .el-pagination__total {
            order: 1;
            width: 50%;
            text-align: left;
        }

        .el-pagination__sizes {
            order: 2;
            width: 50%;
            text-align: right;
        }

        .el-pagination .btn-prev,
        .el-pagination .el-pager,
        .el-pagination .btn-next {
            order: 3;
            width: 100%;
            text-align: center;
            margin: 10px 0;
        }

        .el-pagination .el-pagination__jump {
            order: 4;
            width: 100%;
            text-align: center;
        }
    }
</style>
